import { message } from "antd";
import { History } from "history";
import { MyAxios } from "../../config/http";
import { Storage } from "../../config/auth";

export interface ILoginForm {
  username: string;
  password: string;
  remember: boolean;
}

//callBack为一个回调函数
export function loginAction(
  form: ILoginForm,
  history: History,
  setLoading: Function,
  callBack: Function
) {
  setLoading(true);
  const { username, password, remember } = form;
  MyAxios.axios
    .post("user/login", {
      username,
      password
    })
    .then(res => {
      setLoading(false);
      console.log("typeof res", typeof res);
      console.log("res", res);

      const data: string = res.data;

      console.log("请求结果", data);
      // 存入storage
      const storageRes: boolean = Storage.setToken(data, remember);
      if (storageRes) {
        callBack();
      } else {
        message.error("Token不合法,请重新登录");
      }
    })
    .catch(e => {
      setLoading(false);
      // 当自定义的code不等于SUCCESS时,或者当http状态为不等于200时触发
      // catch代码块中写具体业务需求的错误信息
    });
}
